package cn.edu.njuit.server.ugcnote.ugcnoteserver.security;

import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.UserInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.repository.UserInfoRepository;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.security.TokenService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;

@Service
public class JwtTokenService implements TokenService {
    @Value("${jwt.key}")
    String jwtSecret;
    @Autowired
    UserInfoRepository userInfoRepository;
    @Override
    public String getToken(String login) {
        //使用已配置的秘钥初始化jwt签名工具，此处jwtSecret通过@Value注入使用
        Algorithm algorithm = Algorithm.HMAC256(this.jwtSecret);
        //使用jwt工具包创建jwt标准令牌
        String token = JWT.create()//创建令牌
                .withClaim("login",login)//设置数据体，加入login登录名信息
                .withExpiresAt(Date.from(Instant.now().plusMillis(30*60*1000)))//设置令牌过期时间戳
                .sign(algorithm);//设置签名
        return token;
    }

    @Override
    public UserInfo getUser(String token) {
        Algorithm algorithm = Algorithm.HMAC256(this.jwtSecret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        Claim loginClaim=jwt.getClaim("login");
        String login=loginClaim.asString();
        UserInfo userToken = userInfoRepository.findByUserName(login);

        return userToken;
    }
}
